<template>
    <div class="product">
        <header>
            <div class="product-empty-images" v-if="emptyImageUrls"/>
            <van-swipe class="product-images" indicator-color="white" v-else>
                <van-swipe-item v-for="imageUrl in imageUrls" :key="imageUrl">
                    <van-image width="100%" lazy-load :src="imageUrl"/>
                </van-swipe-item>
            </van-swipe>
            <van-skeleton :row="2" :row-width="['20%', '100%']" :loading="loading">
                <wing-blank>
                    <white-space/>
                    <price :value="product.price" :size="30"/>
                    <white-space/>
                    <span>{{product.name}}</span>
                </wing-blank>
            </van-skeleton>
            <white-space/>
        </header>
        <white-space/>
        <van-cell-group :border="false">
            <van-skeleton :row="1" row-width="100%" :loading="loading">
                <product-cell name="发货" :value="'销量' + product.totalSales">
                    <template v-slot:content>
                        <van-icon name="location-o"/>
                        {{shippingOrigin}}
                        <div class="divider"/>
                        快递: {{shippingCost}}
                    </template>
                </product-cell>
            </van-skeleton>
        </van-cell-group>
        <white-space/>
        <van-cell-group :border="false">
            <product-cell name="选择" @click="handleOptionSelectionClick" arrow>
                <template v-slot:content>{{optionSelectionsStringify}}</template>
            </product-cell>
        </van-cell-group>
        <white-space/>
        <div class="product-reviews">
            <van-cell-group :border="false">
                <van-cell :border="false" title="商品评价" value="查看全部">
                    <template #right-icon>
                        <van-icon name="arrow" class="van-cell__right-icon"/>
                    </template>
                </van-cell>
            </van-cell-group>
        </div>
        <white-space/>
        <product-store :id="product.storeId"/>
        <white-space/>
        <product-selection v-model="optionSelectionVisible"
                           :product="product"
                           :initial-variant="variant"
                           :ok-visible="optionSelectionOkVisible"
                           :add-to-cart-visible="optionSelectionAddToCartVisible"
                           :add-to-cart-loading="addToCartLoading"
                           :buy-visible="optionSelectionBuyVisible"
                           :buy-loading="buyLoading"
                           :ok-loading="addToCartLoading || buyLoading"
                           @change-variant="handleChangeVariant"
                           @add-to-cart="handleAddToCart"
                           @buy="handleBuy"
                           @ok="handleOk"/>
        <product-action>
            <product-action-icon icon="shop-o" text="店铺" :to="'/stores/' + product.storeId"/>
            <product-action-icon icon="cart-o" text="购物车" to="/cart"/>
            <product-action-icon icon="like" text="喜欢" color="#ff5000" @click="handleUnfollowingProduct" v-if="productFollowing"/>
            <product-action-icon icon="like-o" text="喜欢" @click="handleFollowingProduct" v-else/>
            <product-action-button type="warning" text="加入购物车" @click="handleAddToCartClick"/>
            <product-action-button type="danger" text="立即购买" @click="handleBuyClick"/>
        </product-action>
    </div>
</template>

<script>
  import { Cell, CellGroup, Icon, Image, NavBar, Skeleton, Swipe, SwipeItem, Tag, Toast } from "vant"
  import * as _ from "lodash"
  import { browsing, cart, catalog, checkout, follow, message, order, security } from "@mall/api-services"
  import Price from "@/components/Price"
  import WhiteSpace from "@/components/WhiteSpace"
  import WingBlank from "@/components/WingBlank"
  import ProductAction from "@/views/product/ProductAction"
  import ProductActionIcon from "@/views/product/ProductActionIcon"
  import ProductActionButton from "@/views/product/ProductActionButton"
  import ProductCell from "@/views/product/ProductCell"
  import ProductStore from "@/views/product/ProductStore"
  import { ProductSelection } from "@/components/product"

  const BUY_OK_TYPE = "buy", ADD_TO_CART_OK_TYPE = "add_to_cart"

  export default {
    name: "Product",
    components: {
      ProductSelection,
      ProductStore,
      ProductCell,
      ProductActionButton,
      ProductActionIcon,
      ProductAction,
      WingBlank,
      WhiteSpace,
      Price,
      [Cell.name]: Cell,
      [CellGroup.name]: CellGroup,
      [Icon.name]: Icon,
      [Image.name]: Image,
      [NavBar.name]: NavBar,
      [Skeleton.name]: Skeleton,
      [Swipe.name]: Swipe,
      [SwipeItem.name]: SwipeItem,
      [Tag.name]: Tag,
    },
    props: {
      id: String,
    },
    watch: {
      "$route": "refreshProduct",
      product: function(product) {
        if (_.isEmpty(product.id)) {
          return
        }
        const { variants } = product
        if (!_.isEmpty(variants)) {
          this.variant = _.first(variants)
        }
        console.log(product)
        this.refreshFollowingProduct()
        this.addBrowsingProduct()
      },
    },
    computed: {
      optionSelectionsStringify() {
        const { variant } = this
        const { optionSelections } = variant
        return _.isEmpty(optionSelections) ? "请选择规格"
          : _.chain(optionSelections).map(selection => selection.value).join("，").value()
      },
      emptyImageUrls() {
        return _.isEmpty(this.imageUrls)
      },
      imageUrls() {
        const { variant, product } = this
        const { imageUrls } = variant
        return _.isEmpty(imageUrls) ? product.imageUrls : imageUrls
      },
      shippingOrigin() {
        const { product } = this
        const { shippingOrigin } = product
        if (_.isUndefined(shippingOrigin)) {
          return "中国"
        }

        function simpleProvince(province) {
          if (_.isUndefined(province)) {
            return "中国"
          }
          const suffixes = ["省", "市", "壮族自治区", "回族自治区", "维吾尔自治区", "自治区", "特别行政区"]
          for (const suffix of suffixes) {
            if (_.endsWith(province, suffix)) {
              return _.trimEnd(province, suffix)
            }
          }
        }

        function simpleCity(city) {
          if (_.isUndefined(city)) {
            return ""
          }
          const suffixes = ["市", "县", "盟", "朝鲜族自治区", "土家族苗族自治州", "土家族苗族自治州", "省直辖县", "黎族自治县", "地区"]
          for (const suffix of suffixes) {
            if (_.endsWith(city, suffix)) {
              return _.replace(city, suffix, "")
            }
          }
        }

        const province = simpleProvince(shippingOrigin.province)
        const origin = [province]
        const city = simpleCity(shippingOrigin.city)
        if (province !== city) {
          origin.push(city)
        }
        return `${_.join(origin, "")}`
      },
      shippingCost() {
        const { product } = this
        if (product.freeShipping) {
          return "免运费"
        }

        if (product.fixedShippingCost) {
          return `${product.fixedShippingCost}元`
        }

        return "免运费"
      },
    },
    data() {
      return {
        loading: false,
        product: new catalog.Product(),
        variant: new catalog.ProductVariant(),
        optionSelectionVisible: false,
        optionSelectionOkVisible: false,
        optionSelectionAddToCartVisible: true,
        optionSelectionBuyVisible: true,
        optionSelectionOkType: BUY_OK_TYPE,
        buyLoading: false,
        addToCartLoading: false,
        productFollowing: false,
      }
    },
    created() {
      this.refreshProduct()
    },
    methods: {
      showOk() {
        this.optionSelectionVisible = true
        this.optionSelectionOkVisible = true
        this.optionSelectionAddToCartVisible = false
        this.optionSelectionBuyVisible = false
      },
      addBrowsingProduct() {
        const customerId = security.SecurityUserHolder.getUserId()
        browsing.BrowsingProductServiceV1.addBrowsingProduct(customerId, this.id)
      },
      refreshProduct() {
        const { id } = this
        console.log(id)
        if (id) {
          this.loading = true
          catalog.ProductServiceV1.getProduct(id)
            .then(product => {
              if (_.isEmpty(product) || product.id !== id) {
                this.$router.replace(`/products/${id}/404`)
              } else {
                this.product = product
              }
            })
            .finally(() => this.loading = false)
        } else {
          this.$router.replace(`/products/${id}/404`)
        }
      },
      refreshFollowingProduct() {
        const customerId = security.SecurityUserHolder.getUserId()
        follow.FollowServiceV1.checkFollowingProduct(customerId, this.id)
          .then(productFollowing => this.productFollowing = productFollowing)
      },
      handleFollowingProduct() {
        this.productFollowing = true
        const customerId = security.SecurityUserHolder.getUserId()
        follow.FollowServiceV1.followingProduct(customerId, this.id)
          .then(() => Toast("关注成功"))
          .catch(() => this.productFollowing = false)
      },
      handleUnfollowingProduct() {
        this.productFollowing = false
        const customerId = security.SecurityUserHolder.getUserId()
        follow.FollowServiceV1.unfollowingProduct(customerId, this.id)
          .then(() => Toast("取消关注"))
          .catch(() => this.productFollowing = true)
      },
      handleOptionSelectionClick() {
        this.optionSelectionVisible = true
        this.optionSelectionOkVisible = false
        this.optionSelectionAddToCartVisible = true
        this.optionSelectionBuyVisible = true
      },
      handleAddToCartClick() {
        this.showOk()
        this.optionSelectionOkType = ADD_TO_CART_OK_TYPE
      },
      handleBuyClick() {
        this.showOk()
        this.optionSelectionOkType = BUY_OK_TYPE
      },
      handleChangeVariant(variant) {
        this.variant = variant
      },
      handleOk(item) {
        const { optionSelectionOkType } = this
        if (optionSelectionOkType === ADD_TO_CART_OK_TYPE) {
          this.handleAddToCart(item)
        } else if (optionSelectionOkType === BUY_OK_TYPE) {
          this.handleBuy(item)
        }
      },
      handleAddToCart(item) {
        this.addToCartLoading = true
        const customerId = security.SecurityUserHolder.getUserId()
        cart.CartServiceV1.addCartItem(customerId, item)
          .then(() => Toast.success("添加成功"))
          .then(() => this.optionSelectionVisible = false)
          .catch(({ response }) => Toast(message.getResponseMessage(response)))
          .finally(() => this.addToCartLoading = false)
      },
      handleBuy(item) {
        this.buyLoading = true
        const aCheckout = new checkout.Checkout()
        const aItem = new checkout.CheckoutItem()
        aItem.productId = item.productId
        aItem.variantId = item.variantId
        aItem.quantity = 1
        aCheckout.items = [aItem]
        aCheckout.source = order.OrderSource.Browser
        checkout.CheckoutServiceV1.createCheckout(aCheckout)
          .then(checkout => this.$router.push(`/checkouts/${checkout.id}`))
          .catch(({ response }) => Toast(message.getResponseMessage(response)))
          .finally(() => this.buyLoading = false)
      },
    },
  }
</script>

<style lang="scss" scoped>
    @import "../../styles/variables";

    .product {
        background: $background-color;

        header {
            background: #fff;
        }

        .product-empty-images {
            height: 340px;
            width: 100%;
        }
    }

    .product-reviews {

    }

    .divider {
        margin: 0 8px;
        border: 0;
        position: relative;

        &:after {
            content: ' ';
            position: absolute;
            left: 0;
            bottom: 0;
            top: -6px;
            background: $gray-4;
            width: 2px;
            height: 12px;
            transform: scaleX(0.5);
            transform-origin: 0 0;
        }
    }

</style>
